#pragma once

#include <eosiolib/asset.hpp>
#include <eosiolib/eosio.hpp>

#include <string>
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <vector>
#include <eosiolib/transaction.hpp>
#include <eosiolib/crypto.h>

namespace eosio
{
class tools : public contract
{
  public:
    static vector<std::string> split(const std::string &s, const std::string &seperator)
    {
        vector<std::string> result;
        typedef std::string::size_type string_size;
        string_size i = 0;

        while (i != s.size())
        {
            //找到字符串中首个不等于分隔符的字母；
            int flag = 0;
            while (i != s.size() && flag == 0)
            {
                flag = 1;
                for (string_size x = 0; x < seperator.size(); ++x)
                    if (s[i] == seperator[x])
                    {
                        ++i;
                        flag = 0;
                        break;
                    }
            }

            //找到又一个分隔符，将两个分隔符之间的字符串取出；
            flag = 0;
            string_size j = i;
            while (j != s.size() && flag == 0)
            {
                for (string_size x = 0; x < seperator.size(); ++x)
                    if (s[j] == seperator[x])
                    {
                        flag = 1;
                        break;
                    }
                if (flag == 0)
                    ++j;
            }
            if (i != j)
            {
                result.push_back(s.substr(i, j - i));
                i = j;
            }
        }
        return result;
    }

    static std::string to_hex( const char* d, uint32_t s ) 
    {
        std::string r;
        const char* to_hex="0123456789abcdef";
        uint8_t* c = (uint8_t*)d;
        for( uint32_t i = 0; i < s; ++i )
            (r += to_hex[(c[i]>>4)]) += to_hex[(c[i] &0x0f)];
        return r;
    }

    static std::string getTxid() {
        checksum256 h;
		auto size = transaction_size();
		char buf[size];
		uint32_t read = read_transaction( buf, size );
		eosio_assert( size == read, "read_transaction failed");
		sha256(buf, read, &h);

		char bufs[2];

		std::string txid = "";
        for(int i = 0; i < sizeof(h.hash); i++) {
            sprintf(bufs, "%02x", h.hash[i]);
			txid = txid + bufs;
        }

		return txid;
    }

    static std::string stringToSha256(std::string str) {
        std::string tostr = "";
        char bufs[2];
        const char *charstr = str.c_str();
        checksum256 sha;
        sha256( charstr, sizeof(charstr), &sha );
        printhex( &sha, sizeof(sha) );
        for(int i = 0; i < sizeof(sha.hash); i++) {
            sprintf(bufs, "%02x", sha.hash[i]);
			tostr = tostr + bufs;
        }
        //print(tostr);
        return tostr;
    }
};
} // namespace eosio